import time
import os
import json


def replace_file(path):
  # if '.java' not in path:
  #   return

  t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  # 读入
  try:
    f = open(path, "r", encoding="utf-8")
    # 获取内容
    str1 = f.read()
    # 替换内容
    str2 = str1.replace("cn.heisai", "com.lookdoor").replace("* @author Heisai", "* @author Lookdoor  @date " + t)

    ff = open(path, "w")
    # 将信息写入缓冲区
    ff.write(str2)
    # 刷新缓冲区
    ff.flush()
  except Exception:
    print("Error: 没有找到文件或读取文件失败:" + path)


def check_dir(d):
  list_files = os.listdir(d)
  for i in list_files:
    item_file = os.path.join(d, i)
    if os.path.isdir(item_file):
      check_dir(item_file)
      print(item_file)
    else:
      replace_file(item_file)


## 遍历文件夹，并将文件结构写入json中，为代码生成提供辅助
def check_dir_dict(d):
  dict_list = []
  list_files = os.listdir(d)
  for i in list_files:
    if 'DS_Store' in i:
      continue
    file_dict = {'name': i}
    item_file = os.path.join(d, i)
    if os.path.isdir(item_file):
      file_dict['isDir'] = True
      list = check_dir_dict(item_file)
      if (len(list) > 0):
        file_dict['list'] = list
    else:
      file_dict['isDir'] = False
      file_dict['isRes'] = True
    dict_list.append(file_dict)
  return dict_list


def write_in_json(dict):
  with open("jupiter-system-ui.json", "w") as f:
    json.dump(dict, f)
    print("加载入文件完成...")


dir = r"/Users/edgar/workspace/jupiter-code-generator/src/main/resources/template/jupiter-system-ui"

dict = check_dir_dict(dir)
write_in_json(dict)
